package medium;

/**
 * 592. 分数加减运算
 * 地址：https://leetcode.cn/problems/fraction-addition-and-subtraction/description/
 */
public class 分数加减运算_592 {
    public static void main(String[] args) {
        System.out.println(fractionAddition("1/3-1/2"));
    }

    public static String fractionAddition(String expression) {
        int n = expression.length();
        int x = 0, y = 1;
        int index = 0;
        while(index < n) {
            // 获取分子
            int z = 0, sign = 1;
            if (expression.charAt(index) == '-' || expression.charAt(index) == '+') {
                sign = expression.charAt(index++) == '-' ? -1 : 1;
            }
            while(index < n && Character.isDigit(expression.charAt(index))) {
                z = z * 10 + expression.charAt(index) - '0';
                index++;
            }
            z = z*sign;

            // 获取分母
            index++;
            int m = 0;
            while(index < n && Character.isDigit(expression.charAt(index))) {
                m = m * 10 + expression.charAt(index) - '0';
                index++;
            }

            x = x * m + z * y;
            y = y * m;
        }

        if (x == 0) {
            return "0/1";
        }

        int gcd = getGcd(Math.abs(x), y);
        return x/gcd + "/" + y/gcd;
    }

    public static int getGcd(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
}
